package com.awspaas.user.apps.cpq.controller;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.io.FilenameUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import com.actionsoft.bpms.bo.engine.BO;
import com.actionsoft.bpms.commons.formfile.model.FormFileModel;
import com.actionsoft.bpms.commons.formfile.model.delegate.FormFile;
import com.actionsoft.bpms.commons.mvc.view.ResponseObject;
import com.actionsoft.bpms.server.UserContext;
import com.actionsoft.sdk.local.SDK;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

public class CPQ_getExcelFileWeb {

	public String getExcelFile(UserContext userContext, String bindId, String datas) throws Exception {
		String tmpfilePath=SDK.getAppAPI().getProperty("com.awspaas.user.apps.cpq", "tmpfilePath");
		 String openDecryptPath = tmpfilePath + "/" + bindId;	
		try {
			// 将数组转换为列表
			JSONArray mList=JSONObject.parseArray(datas);	
			//对模块中有计算公式的物料进行数量计算
			//单栋成套设备价格合计
			BigDecimal zj=new BigDecimal("0");
			//单栋设备价格小计
			BigDecimal xj=new BigDecimal("0");
			Map<String, String> nameMap=new HashMap<String, String>();
			for (int i = 0; i < mList.size(); i++) {
				JSONObject json = (JSONObject) mList.get(i);
				String name=json.getString("XTMC");
				String bjdjg=json.getString("BJDJG");
				BigDecimal bj=new BigDecimal(bjdjg);
				zj=zj.add(bj);
				if(!name.equals("安装费")) {
					xj=xj.add(bj);
				}
				nameMap.put(name.equals("运输费")?"运输":name.equals("安装费")?"单栋安装服务价格小计":name, bjdjg);
			}
			nameMap.put("单栋设备价格小计", xj.toString());
			nameMap.put("单栋成套设备价格合计", zj.toString());
			System.out.println("nameMap："+nameMap.toString());
			//获取表单上传的销售提供的报价单附件。
			BO bo=SDK.getBOAPI().query("BO_EU_CPQ_PROJECT_MSG").bindId(bindId).detail();
			List<FormFile> files=SDK.getBOAPI().getFiles(bo.getId(), "XMCBFJ");
			
		       Map<String, String> mapFileName=new HashMap<String, String>();
		       Map<String, String> map=new HashMap<String, String>();
		       for (int i=0;i<files.size();i++) {
					String name = files.get(i).getFileName();// 文件名称
					mapFileName.put(name, i+bindId);
					map.put(i+bindId, name);
			 }
		       for (FormFile formFile : files) {
		    	 //1.将附件下载到指定的目录中
					InputStream in = null;
					
					String name = formFile.getFileName();// 文件名称
					String extension = FilenameUtils.getExtension(name);
					String i=mapFileName.get(name);
					String newName=i+"."+extension;
					//System.out.println("name:"+name);
					// 读取文件
					in = SDK.getBOAPI().getFile(formFile.getId());
					// 得到图片的二进制数据，以二进制封装得到数据，具有通用性
					ByteArrayOutputStream outStream = new ByteArrayOutputStream();
					// 创建一个Buffer字符串
					byte[] buffer = new byte[1024];
					// 每次读取的字符串长度，如果为-1，代表全部读取完毕
					int len = 0;
					// 使用一个输入流从buffer里把数据读取出来
					while ((len = in.read(buffer)) != -1) {
						// 用输出流往buffer里写入数据，中间参数代表从哪个位置开始读，len代表读取的长度
						outStream.write(buffer, 0, len);
					}
					// 关闭输入流
					in.close();
					byte[] databyte = outStream.toByteArray();
					outStream.close();
					// 创建指定目录文件
					//File newfile = new File("F:\\tmp_file\\" + "toDoDecrypt" + bindId + "\\" + name);
					File newdirectory = new File( tmpfilePath+ "/" + bindId);
					//File newfile = new File( tmpfilePath+ "/toDoDecrypt" + bindId + "/" + name);
					File newfile = new File( newdirectory, name);
					// 判断文件夹是否存在
					//if (!newfile.exists()) {
					if (!newdirectory.exists()) {
						// 创建文件夹
						//newdirectory.getParentFile().mkdirs();
						newdirectory.mkdirs();
						// 创建文件
						newfile.createNewFile();						  
					}
					// 创建输出流
					FileOutputStream fileOutputStream = new FileOutputStream(newfile);
					// 写入数据
					fileOutputStream.write(databyte);
					// 关闭输出流
					fileOutputStream.close();				
		       }
		   	File openDecryptfiles = new File(openDecryptPath);
		   	String[] openDecryptfileslist = openDecryptfiles.list();
		   	for (String openDName : openDecryptfileslist) {
		   		String temp = openDecryptPath + "/" + openDName;
				System.out.println("PATH:"+temp);
				File file = new File(temp);// 待读取文件,表示在项目根目录下
				FileInputStream fileInputStream = new FileInputStream(file);
	               Workbook workbook = new XSSFWorkbook(fileInputStream);
			       try  {			    	   
			              Sheet sheet = workbook.getSheetAt(0);			              
			              for (Row row : sheet) {
			                  for (Cell cell : row) {			                	 
			                      if (cell.getCellType() == CellType.STRING ) {	
			                    	
			                    	  if(!cell.getStringCellValue().isEmpty()) {
			                    		  String name=cell.getStringCellValue().trim(); 
			                    		  if( nameMap.containsKey(name)) {
			                    			  System.out.println("name:"+name+",value:"+nameMap.get(name));
			                    			// 获取右侧单元格，如果不存在则创建，判断右侧第四列是不是合并单元格如果是则在第三列添加数字，如果不是则在第四列添加数字。
					                          Cell rightCell = row.getCell(cell.getColumnIndex() + 4);
					                          if (rightCell == null) {
					                              rightCell = row.createCell(cell.getColumnIndex() + 4);
					                          }	
					                          // 3. 检查右侧单元格是否为合并单元格
					                          boolean isRightCellMerged = isRightCellMerged(sheet, rightCell);
					                          if(isRightCellMerged) {
					                        	  Cell rightCellNew = row.getCell(cell.getColumnIndex() + 3);
					                        	  rightCellNew.setCellValue(nameMap.get(name));
					                          }else {
					                        	  rightCell.setCellValue(nameMap.get(name));
					                          }
					                        
			                    		  }
			                    	  }			                         			                          
			                      }
			                  }
			              }			              
			              // 保存修改后的文件
			              FileOutputStream fos = new FileOutputStream(temp);
			              try  {
			                  workbook.write(fos);
			                 
			              }catch (Exception e) {
							throw e;
						}finally {
							fos.close();
						}			              
			          } catch (Exception e) {
			              e.printStackTrace();
			          }finally {
			        	  fileInputStream.close();
			        	  workbook.close();
					}				
		   	}
		   	//将赋值完的文件上传到表单附件上
		  	File upfile = new File(openDecryptPath);
		   	String[] upfiles = upfile.list();
		  //将原有附件进行删除
        	String jmfj=bo.getString("XMBJFJ");
        	if(!jmfj.isEmpty()) {
        		SDK.getBOAPI().removeFiles(bo.getId(), "XMBJFJ");
        	}
		 	for (String openDName : openDecryptfileslist) {
		   		String temp = openDecryptPath + "/" + openDName;
				System.out.println("PATH:"+temp);
				File file = new File(temp);// 待读取文件,表示在项目根目录下
				FileInputStream fileInputStream = new FileInputStream(file);
				FormFileModel fModel = new FormFileModel();
				fModel.setAppId("com.awspaas.user.apps.cpq");				
				//String extension = FilenameUtils.getExtension(openDName);
				//String names=openDName.replace("."+extension, "");
				//String fileName=map.get(names);
				fModel.setFileName(openDName);
				fModel.setBoName("BO_EU_CPQ_PROJECT_MSG");
				//fModel.setSecurityLevel(mj);
				fModel.setProcessInstId(bindId);
				fModel.setBoItemName("XMBJFJ");
				fModel.setBoId(bo.getId());
				SDK.getBOAPI().upFile(fModel, fileInputStream);
				fileInputStream.close();
		 	
		 	}		   			   				
		 	 ResponseObject ro = ResponseObject.newOkResponse();
				return ro.toString();
		} catch (Exception e) {
			
				throw e;

		}finally {
			System.gc();			
			// 4.删除生成的本地文件
		      deleteFile(openDecryptPath);
		    
		}
		
	}
	// 删除文件 或者 清除文件夹下的所有文件
			public static void deleteFile(String filePath) {
				File file = new File(filePath);
				if (file.isFile()) // 判断是否为文件，是，则删除
				{
					file.delete();
				} else // 不为文件，则为文件夹
				{
					String[] childFilePath = file.list();// 获取文件夹下所有文件相对路径
					for (String path : childFilePath) {
						deleteFile(file.getAbsoluteFile() + "/" + path);// 递归，对每个都进行判断
					}
					file.delete(); // 如果不保留文件夹本身 则执行此行代码
				}
			}
	 private static boolean isRightCellMerged(Sheet sheet, Cell cell) {
	        int rowIndex = cell.getRowIndex();
	        int colIndex = cell.getColumnIndex(); // 右侧单元格列索引
	        
	        // 遍历所有合并区域
	        for (int i = 0; i < sheet.getNumMergedRegions(); i++) {
	            CellRangeAddress region = sheet.getMergedRegion(i);
	            if (region.isInRange(rowIndex, colIndex)) {
	                return true;
	            }
	        }
	        return false;
	    }
	
}
